package org.jbase.admin.security;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jbase.admin.entity.sys.Admin;
import org.jbase.admin.entity.sys.Role;
import org.jbase.admin.service.sys.AdminService;
import org.jbase.admin.service.sys.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminAuthorizingRealm extends AuthorizingRealm {
	private static final Logger L = LoggerFactory.getLogger(AdminAuthorizingRealm.class);

	@Autowired
	private AdminService adminService;

	@Autowired
	private RoleService roleService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String currentUsername = (String) super.getAvailablePrincipal(principals);
		L.debug("username:  {}", currentUsername);
		if (currentUsername != null) {
			Admin admin = adminService.fetchByName(currentUsername);
			List<Role> listByAdminId = roleService.listByAdminId(admin.getId());
			if (admin == null || listByAdminId == null || listByAdminId.isEmpty()) {
				return null;
			}
			SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
			for (Role role : listByAdminId) {
				simpleAuthorInfo.addRole(role.getEnname());
			}
			return simpleAuthorInfo;
		}
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Admin admin = adminService.fetchByName(token.getUsername());
		if (admin != null) {
			SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(admin.getLoginName(),
					admin.getPassword(), this.getName());

			return simpleAuthenticationInfo;
		}
		return null;
	}

}
